<?php
namespace Admin\Controller;
use Think\Controller;
//推送消息
class PushMessageController extends CommonController {

    public function send(){
        if (IS_AJAX)
        {
            $id       = I('post.id','','htmlspecialchars');
            $table    = I('post.table','','htmlspecialchars');
            $tem      = I('post.tem','','htmlspecialchars');
            $keyword1 = I('post.keyword1','','htmlspecialchars');
            $keyword2 = I('post.keyword2','','htmlspecialchars');
            $keyword3 = I('post.keyword3','','htmlspecialchars');
            $keyword4 = I('post.keyword4','','htmlspecialchars');
            $keyword5 = I('post.keyword5','','htmlspecialchars');
            $touser   = I('post.touser','','htmlspecialchars');
            $uid      = I('post.uid','','int');
            $appid    = I('post.appid','','htmlspecialchars');
            $secret   = I('post.secret','','htmlspecialchars');
            $game     = I('post.game','','htmlspecialchars');

            $test     = I('post.test','','htmlspecialchars');
            $swoole_server_port    =   '9501';

            if (! empty($test))
            {
                $swoole_server_port    =   '9502';
            }

            $emphasis_keyword   =   I('post.emphasis_keyword','','htmlspecialchars');
            $template_data      =   array();

            if (empty($game))
            {
                $msg['state']   =   -1;
                $msg['error']   =   '游戏标识（英文小写）';
                $this->ajaxReturn ($msg,'JSON');
            }

            if (empty($table))
            {
                $msg['state']   =   -1;
                $msg['error']   =   '请输入推送的表';
                $this->ajaxReturn ($msg,'JSON');
            }

            $where                              =   array();
            $where['wxopen_template_send_id']   =   $id;
            $where['uid']                       =   $uid;
            $where['appid']                     =   $appid;
            $where                              =   array_filter($where);

            if ($uid)
            {
                $template_data = M($table)->where(array('uid'=>$uid))->order('wxopen_template_send_id desc')->limit(1)->select();
            }
            else
            {
                $template_data  =   M($table)->where($where)->group('touser')->order('wxopen_template_send_id desc')->select();
            }

            //模板消息
            $msgssage   =   array();
            if ($keyword1){
                $msgssage['keyword1'] = array(
                    'value'=>$keyword1,
                    'color'=>'#173177',
                );
            }

            if ($keyword2){
                $msgssage['keyword2'] = array(
                    'value'=>$keyword2,
                    'color'=>'#173177',
                );
            }

            if ($keyword3){
                $msgssage['keyword3'] = array(
                    'value'=>$keyword3,
                    'color'=>'#173177',
                );
            }

            if ($keyword4){
                $msgssage['keyword4'] = array(
                    'value'=>$keyword4,
                    'color'=>'#173177',
                );
            }

            if ($keyword5){
                $msgssage['keyword5'] = array(
                    'value'=>$keyword5,
                    'color'=>'#173177',
                );
            }

            //数据拼装
            $redis = new \Redis();
            $redis->connect('127.0.0.1',6379);
            $access_token = $this->redis_access_token($appid,$secret,$redis);

            $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";

            if(empty($tem))
            {
                $tem = "JYhnftZ3mQ1OBdQ9a2EjTYAQomZt-gnVOJbLRWj4WYM";
            }

            //保存已经发过的用户
            $worldcup_member        =   $redis->get($game.'_member');
            if (! empty($worldcup_member))
            {
                $worldcup_member        =   json_decode($worldcup_member,true);
            }
            else
            {
                $worldcup_member    =   array();
            }

            //记录加入对的的数量
            $list_nums              =   0;

            //链接swoolw服务器
            $client = new \swoole_client(SWOOLE_SOCK_TCP);
            //连接到服务器
            if (!$client->connect('127.0.0.1', $swoole_server_port, 0.5))
            {
                $msg['state']   =   -1;
                $msg['error']   =   'swoole服务器连接失败';
                $this->ajaxReturn ($msg,'JSON');
            }

            foreach($template_data as $key=> $value)
            {
                if (! in_array($value['touser'], $worldcup_member) && $value['form_id'] !=  'the formId is a mock one' )
                {
                    $data = array(
                        'touser'=>$value['touser'],
                        'template_id'=>$tem,
                        'page'=>'pages/index/index?appid=wx6b1c7907c5733fc9&page=pages/index/index?appid2=wxb2dfa5282782f280',    //pages/index/index?appid=wx6b1c7907c5733fc9&appid2=wxb2dfa5282782f280  pages/index/index
                        'form_id'=>$value['form_id'],
                        'data'=>$msgssage,
                        'emphasis_keyword'=>$emphasis_keyword,
                    );

                    //推送数据写入redis队列
                    $post_data 			=	array();
                    $post_data['data']	=	$data;
                    $post_data['url']	=	$url;
                    $post_data['id']	=	$value['wxopen_template_send_id'];
                    $redis->rPush('push_'.$game,json_encode($post_data));

                    //用户追加到推送约束list里去
                    $worldcup_member[]  =   $value['touser'];
                    $member_data    =   json_encode($worldcup_member);
                    $redis->set($game.'_member', $member_data);

                    $list_nums++;
                }
            }


            if (!empty($list_nums))
            {
                //向swoole服务端发送推送请求
                $data			    =	array();
                $data['game']	    =	$game;
                $data['action']     =	'Push';
                $data['test']       =   false;
                $data['table']      =   $table;
                $data['call_back']  =   'https://api.beikg.cn/home/SwooleClient/api_accept';    //返回跟更新或删除数据的接口 http://test.beikg.cn/home/index/api_accept
                $msg 			    =	serialize($data);

                $return_msg         =   array();
                //向服务器发送数据
                if (!$client->send($msg))
                {
                    $return_msg['state']   =   -1;
                    $return_msg['error']   =   '发送到swoole失败';
                }
                else
                {
                    $return_msg['state']   =   200;
                    $return_msg['error']   =   '发送swoole成功';
                }
                $client->close();
                //关闭连接
                $this->ajaxReturn ( $return_msg,'JSON');

            }
            else
            {
                $msg['state']   =   -1;
                $msg['error']   =   '发送失败';
                $this->ajaxReturn ($msg,'JSON');
            }
        }

        $data           =   array();
        $where['id']    =   I('get.id','','htmlspecialchars');
        if (! empty($where['id']))
        {
            $field      =   array('id','logo','appid','secret','url','envversion','content','title','isshow','sort','module','user_table','template_table','other_name','template_id');
            $data['app_info']  =   M('app')->where($where)->field($field)->find();
        }

        $this->assign("data",$data);
        $this->display('send');
    }

    public function send_status()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);

        $game           =   $_REQUEST['game'];
        $game_message   =	'push_'.$game;
        $message 	    =	'update_'.$game;    //已经发送的
        $success_message=	'successed_'.$game;

        $worldcup_member        =   $redis->get($game.'_member');
        $worldcup_member        =   json_decode($worldcup_member,true);

        $redis->set($game.'_member','');

        print_r($worldcup_member);

        $loop 	=	true;
        while ($loop)
        {
            $value = $redis->lpop($game_message);

            if(! empty($value))
            {
                //投递异步任务
                print_r($value);

            }
            else
            {
                $loop	=	false;
            }
        }

        $loop_success 	=	true;
        while ($loop_success)
        {
            $value = $redis->lpop($success_message);

            if(! empty($value))
            {
                //投递异步任务
                echo "id=".$value."</br>";
            }
            else
            {
                $loop_success	=	false;
            }
        }

        $loop_ed 	=	true;
        while ($loop_ed )
        {
            $valued = $redis->lpop($message);

            if(! empty($valued))
            {
                //投递异步任务
                echo "id=".$valued."</br>";
            }
            else
            {
                $loop_ed	=	false;
            }
        }

    }

    /**
     * 发送成功的用户
     */
    public function success_user()
    {
        if (IS_AJAX)
        {
            $game   =   I('post.game','','htmlspecialchars');
            $table  =   I('post.table','','htmlspecialchars');

            if (! empty($game) && ! empty($table))
            {
                $success_message	=	'success_'.$game;
                $redis = new \Redis();
                $redis->connect('127.0.0.1',6379);

                $insert_data        =   array();
                while(true){
                    try{
                        $value = $redis->lpop($success_message);
                        if(!$value){
                            break;
                        }

                        $insert                 =   array();
                        $insert['touser']       =   $value;
                        $insert['create_time']  =   time();
                        $insert['game']         =   $game;
                        $insert['table']        =   $table;
                        $insert_data[]          =   $insert;

                    }catch(Exception $e){
                        echo $e->getMessage();
                    }
                }

                if(! empty($insert_data))
                {
                    M('swoole_success')->addAll($insert_data);
                }
            }

            $msg['state']   =   1;
            $msg['error']   =   '同步成功';
            $this->ajaxReturn ($msg,'JSON');
        }

        $data                   =   array();
        $data['success_data']   =   M('swoole_success')->select();
        $this->assign("data",$data);
        $this->display('success_user');
    }

    /**
     * 发送失败的的用户
     */
    public function fail_user()
    {
        if (IS_AJAX)
        {
            $game   =   I('post.game','','htmlspecialchars');
            $table  =   I('post.table','','htmlspecialchars');

            if (! empty($game) && ! empty($table))
            {
                $fail_message	=	'fail_'.$game;
                $redis = new \Redis();
                $redis->connect('127.0.0.1',6379);

                $insert_data        =   array();
                while(true){
                    try{
                        $value = $redis->lpop($fail_message);
                        if(!$value){
                            break;
                        }

                        $insert                 =   array();
                        $insert['touser']       =   $value;
                        $insert['create_time']  =   time();
                        $insert['game']         =   $game;
                        $insert['table']        =   $table;
                        $insert_data[]          =   $insert;

                    }catch(Exception $e){
                        echo $e->getMessage();
                    }
                }

                if(! empty($insert_data))
                {
                    M('swoole_fail')->addAll($insert_data);
                }
            }

            $msg['state']   =   1;
            $msg['error']   =   '同步成功';
            $this->ajaxReturn ($msg,'JSON');
        }

        $data                   =   array();
        $data['fail_data']      =   M('swoole_fail')->select();
        $this->assign("data",$data);
        $this->display('fail_user');
    }

    public function show()
    {
        $game       =   'color';
        $table      =   'colour_template_send';
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);

        while(true){
            try{
                $value = $redis->lpop('do_data');
                if(!$value){
                    break;
                }

                $log         =  array();
                $log['log']  =  $value;
                M('yao_log')->add($log);
            }catch(Exception $e){
                echo $e->getMessage();
            }
        }

        $success_message	=	'success_'.$game;
        while(true){
            try{
                $value = $redis->lpop($success_message);
                if(!$value){
                    break;
                }

                $insert                 =   array();
                $insert['touser']       =   $value;
                $insert['create_time']  =   time();
                $insert['game']         =   $game;
                $insert['table']        =   $table;
                M('swoole_success')->add($insert);

            }catch(Exception $e){
                echo $e->getMessage();
            }
        }

        $fail_message	=	'fail_'.$game;
        while(true){
            try{
                $value = $redis->lpop($fail_message);
                if(!$value){
                    break;
                }

                $insert                 =   array();
                $insert['touser']       =   $value;
                $insert['create_time']  =   time();
                $insert['game']         =   $game;
                $insert['table']        =   $table;
                M('swoole_fail')->add($insert);

            }catch(Exception $e){
                echo $e->getMessage();
            }
        }
    }
}